<?php
/*
$Id: ctg-gis-basics.php 49 2011-09-02 13:16:53Z eugim.migue@gmail.com $
*/
require_once 'quickstart-loading-re.php';

$locations = re::relation(array(
	array('name'=>'A', 'x'=>1.0, 'y'=>1.0)
   ,array('name'=>'B', 'x'=>1.0, 'y'=>3.0)
   ,array('name'=>'C', 'x'=>-3.0, 'y'=>3.0)
   ,array('name'=>'D', 'x'=>-2.0, 'y'=>-2.0)
   ,array('name'=>'E', 'x'=>4.0, 'y'=>-2.0)
));


function is_in_radius($tuple){
	return (pow($tuple->x - $tuple->h, 2)  + pow($tuple->y - $tuple->k, 2)) <= pow($tuple->r, 2);
}

$is_submit = isset($_POST['btnSubmit']);

if( $is_submit ){

	$search_space = re::relation(array(
		array('name'=>$_POST['location_center'], 'r'=>(double)$_POST['radius'])
	));

	$origin = $locations->join($search_space)
								  ->rename(array('x'=>'h', 'y'=>'k'))
								  ->project(array('name'), TRUE);
	 
	$in_radius = $locations->join($origin)->where('is_in_radius');
	
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Using re to create a basic Geographical Information System (GIS)</title>
	<style type="text/css">
		html{
			font-family:tahoma;
		}
	</style>
</head>
<body>
	<h2>A Very Basic Geographical Information System</h2>
	<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
		Select Base Location: 
		<select name="location_center">
			<?php
				$sel = isset($_POST['location_center']) ? $_POST['location_center'] : '';
				foreach($locations->toArray() as $tuple){
					$name = $tuple->get('name');
			?>
				<option value="<?php echo $name; ?>" <?php echo ($sel == $name) ? 'selected="selected"' : "";?>>
					<?php echo $tuple->get('name') . ": (x:" . $tuple->get('x') . ", y:" . $tuple->get('y') .")"; ?>
				</option>				
			<?php
				}
			?>
		</select>
		<br/>
		Radius:
		<input type="text" name="radius" value="<?php echo isset($_POST['radius']) ? $_POST['radius'] : '5'; ?>"/>
		<br/>
		<input name="btnSubmit" type="submit" value="Generate Locations within radius">
	</form>
	<?php
		if( $is_submit ){
			$in_radius = $in_radius->toArray();
			if( !empty($in_radius) ){
				echo "<h3>Locations within specified radius</h3>";
				$cnt = 1;
				foreach($in_radius as $tuple){
					echo $cnt . ".) " . $tuple->get('name') . ": (x:" . $tuple->get('x') . ", y:" . $tuple->get('y') . ")";
					echo "<br/>";
					$cnt++;
				}
			}
			else{
				echo "None.";
			}
		}
	?>

</body>
</html>